package cn.itcast.controller;


import cn.itcast.entity.Result;
import cn.itcast.util.RedisMessageConstant;
import cn.itcast.util.SMSUtils;
import cn.itcast.util.ValidateCodeUtils;

import com.aliyuncs.exceptions.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {
    @Autowired
    private JedisPool jedisPool;

    /**
     * 发送预约的验证码
     *
     * @return
     */
    @RequestMapping("/send4Order")
    public Result send4Order(String telephone) {
        try {
            //+ 生成验证码
            Integer validateCode = ValidateCodeUtils.generateValidateCode(6);
            System.out.println(validateCode);
            //+ 调用阿里云发送短信
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, validateCode.toString());
            //+ ==把验证码存到Redis(存5分钟)==
            jedisPool.getResource().setex(telephone + RedisMessageConstant.SENDTYPE_ORDER, 5 * 60 * 10, validateCode.toString());
            return new Result();
        } catch (Exception e) {
            e.printStackTrace();
            return new Result();
        }
    }

    /**
     * 校验验证码
     * @param map
     * @return
     */


    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map) {
        String telephone = (String) map.get("telephone");
        //从Redis中获取缓存的验证码，key为手机号+RedisConstant.SENDTYPE_ORDER
        String codeInRedis = jedisPool.getResource().get(
                telephone + RedisMessageConstant.SENDTYPE_ORDER);
        String validateCode = (String) map.get("validateCode");
        //校验手机验证码
        if (codeInRedis == null || !codeInRedis.equals(validateCode)) {
            return null;
        }
//        Result result = null;
//        //调用体检预约服务
//        try {
//            map.put("orderType", Order.ORDERTYPE_WEIXIN);
//            result = orderService.order(map);
//        } catch (Exception e) {
//            e.printStackTrace();
//            //预约失败
//            return result;
//        }
//        if (result.isFlag()) {
//            //预约成功，发送短信通知
//            String orderDate = (String) map.get("orderDate");
//            try {
//                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, telephone, orderDate);
//            } catch (ClientException e) {
//                e.printStackTrace();
//            }
//        }
//        return result;
        return new Result();
    }


}
